package com.example.autojob.skeleton.db.entity;

import com.example.autojob.skeleton.db.mapper.AutoJobMapperHolder;
import com.example.autojob.skeleton.framework.task.AutoJobTask;
import com.example.autojob.skeleton.model.task.method.MethodTask;

import java.sql.Timestamp;

/**
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-03-15 16:16
 * @email 1158055613@qq.com
 */
public class MethodTask2EntityConvertor implements Task2EntityConvertor<AutoJobMethodTaskEntity> {
    @Override
    public AutoJobMethodTaskEntity convert(AutoJobTask source) {
        AutoJobMethodTaskEntity entity = new AutoJobMethodTaskEntity();
        entity.setId(source.getId());
        entity.setMethodClassName(source.getMethodClass() == null ? "" : source
                .getMethodClass()
                .getName());
        entity.setType(0);
        MethodTask methodTask = (MethodTask) source;
        entity.setMethodName(source.getMethodName());
        entity.setMethodObjectFactory(methodTask
                .getMethodObjectFactory()
                .getClass()
                .getName());
        if (source.getAnnotationId() != null) {
            AutoJobMethodTaskEntity latestVersion = AutoJobMapperHolder.METHOD_TASK_ENTITY_MAPPER.selectLatestAnnotationTask(source.getAnnotationId());
            if (latestVersion != null && latestVersion.getVersion() != null) {
                entity.setVersion(latestVersion.getVersion() + 1);
            } else {
                entity.setVersion(0L);
            }
            entity.setAnnotationId(source.getAnnotationId());
        }
        entity.setBelongTo(source.getBelongTo());
        entity.setTriggerId(source
                .getTrigger()
                .getTriggerId());
        entity.setRunningStatus(source
                .getRunningStatus()
                .getFlag());
        entity.setRunLock(0);
        entity.setStatus(1);
        entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        entity.setAlias(source.getAlias());
        entity.setIsChildTask(source.getIsChildTask() != null && source.getIsChildTask() ? 1 : 0);
        entity.setTaskLevel(source.getTaskLevel());
        entity.setParams(source.getParamsString());
        return entity;
    }
}
